package engine.render;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

import engine.controllers.Keyboard;
import engine.entities.Entity;
import engine.entities.Spatial;

@SuppressWarnings("serial")
public class Render extends JFrame {

	private Canvas canvas;
	private BufferedImage buffer;

	public Render(int width, int height) {
		setSize(width, height);
		canvas = new Canvas();
		canvas.setSize(width, height);
		buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
		add(canvas);
		canvas.setVisible(true);
		pack();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void draw(Entity e) {
		Graphics2D g = (Graphics2D) buffer.getGraphics();
		g.translate(0.0, buffer.getHeight(null));
		g.scale(1.0, -1.0);
		Image sprite = e.getSprite().getLast();
		int x = (int) e.getSpatial().getX();
		int y = (int) e.getSpatial().getY();
		g.drawImage(sprite, x, y, null);
		drawEnergy(e, g);
		repaint();
	}

	public void drawEnergy(Entity e, Graphics g) {
		Spatial spatial = e.getSpatial();
		int x = (int) spatial.getX();
		int y = (int) spatial.getY();
		int height = (int) spatial.getHeight();

		g.setColor(Color.BLACK);
		g.drawRect(x, y + height + 10, 50, 4);
		g.setColor(Color.GREEN);

		float percentage = (float) e.getEnergy().getValue()
				/ (float) e.getEnergy().getMaximum();
		int remaining = (int) (percentage * 49);

		g.fillRect(x + 1, y + height + 10, remaining, 3);
	}

	public void clear() {
		Graphics2D g = (Graphics2D) buffer.getGraphics();
		g.setBackground(Color.WHITE);
		g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
		g.dispose();
	}

	@Override
	public void paint(Graphics g) {
		canvas.getGraphics().drawImage(buffer, 0, 0, null);
	}

	public Keyboard getKeyboardController() {
		Keyboard controller = new Keyboard();
		canvas.addKeyListener(controller);
		return controller;
	}

}
